package tcp.文件上传;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

//上传方法，客户端
public class test {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream outputStream = null;
        FileInputStream file = null;
        InputStream inputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;
        try {
            //1.创建一个socket连接
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 8080);
            //2.创建一个套接字的输出流
            outputStream = socket.getOutputStream();//抽象类是表示字节输出流的所有类的超类。 输出流接收输出字节并将其发送到某个接收器。
            //3.把文件变成文件流，读取文件
            file = new FileInputStream(new File("C:\\Users\\qjw\\Pictures\\Camera Roll\\2019-08-12 135112.jpg"));
            //4.发送文件流
            byte[] wj = new byte[1024];
            int len;
            while ((len = file.read(wj)) != -1) {
                outputStream.write(wj, 0, len);//write将指定的字节写入此输出流
            }

            //5.告诉服务器发送完成
            socket.shutdownOutput();

            //接收服务器发送的文件上传成果
            inputStream = socket.getInputStream();
            byte[] xx = new byte[1024];
            byteArrayOutputStream = new ByteArrayOutputStream();
            int len1;
            while ((len1 = inputStream.read(xx)) != -1) {
                byteArrayOutputStream.write(xx,0,len1);
            }
            System.out.println(byteArrayOutputStream.toString());


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (byteArrayOutputStream!=null){
                    byteArrayOutputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
                if (file != null) {
                    file.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {

            }
        }
    }
}
